package org.lifei.gift.service.impl;

import org.lifei.exception.BusinessException;
import org.lifei.exception.LifeiAssert;
import org.lifei.exception.ResponseCode;
import org.lifei.gift.clients.AuthClient;
import org.lifei.gift.constants.UserConstants;
import org.lifei.gift.domain.LoginUser;
import org.lifei.gift.domain.User;
import org.lifei.gift.domain.UserInfo;
import org.lifei.gift.dto.UserRegisterDTO;
import org.lifei.gift.mapper.UserInfoMapper;
import org.lifei.gift.mapper.UserMapper;
import org.lifei.gift.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.lifei.util.AjaxResult;
import org.lifei.util.encrypt.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author lifei
 * @since 2024-03-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private AuthClient authClient;

    @Override
    public void register(UserRegisterDTO dto) {
        //1、参数校验
        //1、1非空验证 JSR303做了
        //1、2 校验验证码是否匹配
        String phone = dto.getPhone();
        String key = UserConstants.USER_REGISTER_SEND_SMS_KEY+"-"+ phone;
        String codeByRedis = (String) redisTemplate.opsForValue().get(key);
        //如果redis中的数据为空，说明验证码已经过期，提示重新获取
        LifeiAssert.isNotBlank(codeByRedis, ResponseCode.RESPONSE_CODE_400009);
        //如果不为空，我们再比较密码是否一致
        String code = codeByRedis.split(":")[0];
        LifeiAssert.isEq(dto.getVerifyCode(),code,ResponseCode.RESPONSE_CODE_400009);
        //2、密码加密加盐
        String salt = UUID.randomUUID().toString().replace("-","");
        //盐值存入数据库，做登录时，拿着登录时用户输入的铭文密码+盐值，通过MD5算法加密后，和数据库放的密码作比对
        //为了防止暴力破解，我们可以在代码中，在salt+password前后输出一些固定的字符串
        String password = MD5.getMD5("lifei"+salt + dto.getPassword()+"qian");
        //3、保存数据到认证授权中心的t_login_user,并要获取到login_id
        LoginUser loginUser = new LoginUser();
        // 用户注册时,没有输入用户名,所以先随机生成一个字符串作为用户名
        loginUser.setUsername(UUID.randomUUID().toString());
        loginUser.setSalt(salt);
        loginUser.setPassword(password);
        loginUser.setPhone(dto.getPhone());
        loginUser.setType(1);
        AjaxResult ajaxResult = authClient.addOrUpdate(loginUser);
        if(!ajaxResult.isSuccess()){
            // 远程调用授权服务保存登录信息,有可能会报错不成功,如果报错我们就抛出异常,阻止程序继续往下运行
            throw new BusinessException(ajaxResult.getMessage());
        }
        Long loginId =  Long.parseLong(ajaxResult.getResultObj().toString());


        //4、保存数据到t_user t_user_info
        User user = new User();
        user.setCreateTime(new Date().getTime());
        user.setPhone(dto.getPhone());
        user.setPassword(dto.getPassword());
        user.setSalt(null);
        user.setBitState(1L);
        user.setSecLevel(1);
        user.setLoginId(loginId);
        insert(user);
        //info
        UserInfo userInfo = new UserInfo();
        userInfo.setRegTime(new Date().getTime());
        userInfo.setLevel(0);
        userInfo.setGrowScore(0);
        userInfo.setUserId(user.getId());
        userInfoMapper.insert(userInfo);

        //5、给用户发送注册成功的短信通知，消息队列
    }
}
